package com.real.operationalcontrols.基类;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import butterknife.Unbinder;

public abstract class TaskBaseFragment extends Fragment {
    Activity mContext;
    //Fragment的View加载完毕的标记
    private boolean isViewCreated;
    //Fragment对用户可见的标记
    private boolean isUIVisible;
    private boolean isResume;
    protected View mRoot;
    protected Unbinder mRootUnBinder;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = getActivity();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
        //Log.i("gaogao","onViewCreated");
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //Log.i("gaogao","setUserVisibleHint"+isVisibleToUser);
        if (isVisibleToUser) {
            isUIVisible = true;
            lazyLoad();
        } else {
            isUIVisible = false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //Log.i("gaogao","onResume");
        isResume = true;
        lazyLoad();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        int layoutId = getContentLayoutId();

        if (mRoot == null) {
            // 初始化当前的根布局, 但是不在创建时就添加到 container 里面
            mRoot = inflater.inflate(layoutId, container, false);
            // 如果第一次初始化, 创建 mRroot 并且初始化控件
            // initWidget(mRoot);
        } else {
            if (mRoot.getParent() != null) {
                // 把当前 Root 从其父控件中移除
                ((ViewGroup) mRoot.getParent()).removeView(mRoot);
            }
        }
        return mRoot;
    }

    private void lazyLoad() {
        if (isUIVisible && isViewCreated && isResume) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //必须延时加载，防止view还没有创建就赋值
                    loadData();
                }
            }, 300);
        }
    }

    public Activity getmContext() {
        return mContext;
    }

    protected abstract int getContentLayoutId();

    protected abstract void loadData();
}
